#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>

int
main(int argc, char* args[])
{
	int pid, i, fd[2];
	if(pipe(fd) < 0){
		perror("pipe error");
		exit(1);
	}
	
	for(i = 0; i < 2; i ++){
		pid = fork();
		if(pid < 0){
			perror("pid error");
			exit(1);
		}
		else if(!pid) break;
	}

	//ls
	if(i == 0){
		printf("the process is %d\n", getpid());
		close(fd[0]);
		if(dup2(fd[1], STDOUT_FILENO) < 0){
			perror("dup2 error");
			exit(1);
		}
		execlp("ls", "ls", NULL);
		perror("execlp ls error");
		exit(1);
	}

	//wc -l
	else if(i == 1){
		printf("the process is %d\n", getpid());
		close(fd[1]);
		if(dup2(fd[0], STDIN_FILENO) < 0){
			perror("dup2 error");
			exit(1);
		}
		execlp("wc", "wc" , "-l", NULL);
		perror("exec wc error");
		exit(1);
	}
	
	else{
		//close(fd[0]);
		//close(fd[1]);
		int status;

		waitpid(0, &status, 0);
		if(WIFEXITED(status)){
			printf("the child process is %d\n",WEXITSTATUS(status));
		}

		waitpid(0, &status, 0);
		if(WIFEXITED(status)){
			printf("the child process is %d\n",WEXITSTATUS(status));
		}
	}

	exit(0);
}

